﻿using SF.API.Payment.wxpay;
using SF.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.TenPayLibV3;
using SF.Ucenter.api.wxpay;
using System.Collections;
using System.Configuration;
using System.IO;

namespace SF.Ucenter.api
{
    public partial class paypage : System.Web.UI.Page
    {
        public Model.sf_user_info userInfo;
        public string appWhere;
        public String packageValue = "";
        protected int wid = 0;
        protected string otid_str = "", openid = "", rpage = "";
        protected string mch_id, partnerkey, no_url, pay_url, ip_url, code_uri, openid_uri;
        /// <summary>
        /// 订单付款的有效持续时间（单位为分）
        /// </summary>
        protected int expireMinute = 0; 

        protected void Page_Load(object sender, EventArgs e)
        {
            //获取配置文件数据
            IDictionary dict = ConfigurationManager.GetSection("weixinPay") as IDictionary;
            no_url = dict["notify_url"].ToString();     //"/api/wxpay/notify_url.aspx";
            pay_url = dict["paypage_url"].ToString();   //"/api/paypage.aspx";
            ip_url = dict["ip_url"].ToString();         //"http://www.aojieer.net"
            code_uri = dict["code_uri"].ToString();     //"https://open.weixin.qq.com/connect/oauth2/authorize?";
            openid_uri = dict["openid_uri"].ToString(); //"https://api.weixin.qq.com/sns/oauth2/access_token?";

            #region 新的 网页授权access_token
            string code = Request.QueryString["code"];
            if (!string.IsNullOrEmpty(code))
            {
                userInfo = Session[DTKeys.SESSION_ADMIN_INFO] as Model.sf_user_info;
                appWhere = Utils.getWhereByInfo(userInfo.busnieseNum, userInfo.appNum, userInfo.templatesNum);
                Model.sf_appidmanage appModel = new BLL.sf_appidmanage().GetModel(userInfo.appNum);
                WebClient obj = new WebClient();
                string str = obj.GetHtml(string.Concat(openid_uri + "appid=" + appModel.appid + "&secret=" + appModel.appsecret + "&code=", code, "&grant_type=authorization_code"));
                access_base p = SF.Ucenter.api.wxpay.JsonHelper.JsonDeserialize<access_base>(str);
                openid = p.openid;
            }
            else
            {
                userInfo = Session[DTKeys.SESSION_ADMIN_INFO] as Model.sf_user_info;
                //snsapi_base
                string url = ip_url + pay_url;
                otid_str = Request["orderId"];
                string reluri = Server.UrlEncode(url);
                string open = string.Concat(code_uri + "appid=" + userInfo.appNum + "&redirect_uri=", reluri, "&response_type=code&scope=snsapi_base&state=" + otid_str + "#wechat_redirect");
                Response.Redirect(open);
            }

            #endregion



            try
            {
                otid_str = string.IsNullOrEmpty(Request["orderId"]) ? Request["state"] : Request["orderId"];
                if (expireMinute == 0)
                {
                    expireMinute = 30;
                }
                else if (expireMinute == -1)
                {  //如果为-1，则有限期间为1年
                    expireMinute = 60 * 12 * 365;
                }
                if (string.IsNullOrEmpty(otid_str))
                {
                    return;
                }
                if (openid == "" || otid_str == "")
                {
                    return;
                }
                BLL.sf_goods_order otBll = new BLL.sf_goods_order();
                Model.sf_goods_order orderEntity = otBll.GetModel("orderNum='" + otid_str + "' and "+appWhere);
                litout_trade_no.Text = orderEntity.orderNum;
                litMoney.Text = orderEntity.totalMoney.ToString();
                litDate.Text = orderEntity.addTime.ToString();

                System.Data.DataTable detaldt = new BLL.sf_goods_orderdetal().GetList("orderNum='" + otid_str + "' and " + appWhere).Tables[0];
                Model.sf_goods_info goods = new BLL.sf_goods_info().GetModel("goodsNum='" + detaldt.Rows[0]["goodsNum"] + "' and " + appWhere);
                if (detaldt.Rows.Count > 1)
                {
                    goods.names = goods.names + "等";
                }
                WxPayDataV3(Convert.ToDecimal(orderEntity.totalMoney), "购买" + goods.names + orderEntity.totalMoney + "元", orderEntity.orderNum, code);
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 最新接口调用
        /// 2014-11-24
        /// </summary>
        /// <param name="ttFee">支付金额（单位元）</param>
        /// <param name="busiBody">订单内容</param>
        /// <param name="out_trade_no">订单号</param>
        /// <param name="code"></param>
        protected void WxPayDataV3(decimal ttFee, string busiBody, string out_trade_no, string code)
        {
            Model.sf_appidmanage appModel = new BLL.sf_appidmanage().GetModel(userInfo.appNum);
            //先设置基本信息
            string MchId = appModel.weixin_pay_account;

            string partnerKey = appModel.account_pay_key;     // 商户支付密钥Key。登录微信商户后台，进入栏目【账户设置】【密码安全】【API 安全】【API 密钥】

            string notify_url = "http://" + HttpContext.Current.Request.Url.Authority + no_url;

            string timeStamp = "";
            string nonceStr = "";
            string paySign = "";

            string sp_billno = out_trade_no;
            //当前时间 yyyyMMdd
            string date = DateTime.Now.ToString("yyyyMMdd");

            if (null == sp_billno)
            {
                //生成订单10位序列号，此处用时间和随机数生成，商户根据自己调整，保证唯一
                sp_billno = DateTime.Now.ToString("HHmmss") + TenPayV3Util.BuildRandomStr(28);
            }

            try
            {
            //创建支付应答对象
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler packageReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            //初始化

            //packageReqHandler.SetKey(""/*TenPayV3Info.Key*/);

            timeStamp = TenPayV3Util.GetTimestamp();
            nonceStr = TenPayV3Util.GetNoncestr();
            //设置package订单参数
            packageReqHandler.SetParameter("appid", userInfo.appNum);		                            //公众账号ID
            packageReqHandler.SetParameter("attach", busiBody);
            packageReqHandler.SetParameter("body", busiBody);                               //商品描述
            packageReqHandler.SetParameter("mch_id", MchId);		                        //商户号
            packageReqHandler.SetParameter("nonce_str", nonceStr);                          //随机字符串
            packageReqHandler.SetParameter("notify_url", notify_url);		                //接收财付通通知的URL
            packageReqHandler.SetParameter("openid", openid);	                            //用户的openId
            packageReqHandler.SetParameter("out_trade_no", sp_billno);		                //商家订单号
            packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress);    //用户的公网ip，不是商户服务器IP
            packageReqHandler.SetParameter("total_fee", ((int)(ttFee * 100)).ToString());	//商品金额,以分为单位(money * 100).ToString()
            packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());    //交易类型
            string sign = packageReqHandler.CreateMd5Sign("key", partnerKey);
            packageReqHandler.SetParameter("sign", sign);	                                //签名
            string data = packageReqHandler.ParseXML();
            var result = TenPayV3.Unifiedorder(data);
            var res = XDocument.Parse(result);
            string prepayId = res.Element("xml").Element("prepay_id").Value;

            //设置支付参数
            Senparc.Weixin.MP.TenPayLibV3.RequestHandler paySignReqHandler = new Senparc.Weixin.MP.TenPayLibV3.RequestHandler(null);
            paySignReqHandler.SetParameter("appId", userInfo.appNum); 
            paySignReqHandler.SetParameter("timeStamp", timeStamp);
            paySignReqHandler.SetParameter("nonceStr", nonceStr);
            paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
            paySignReqHandler.SetParameter("signType", "MD5");
            paySign = paySignReqHandler.CreateMd5Sign("key", partnerKey);

            packageValue = "";
            packageValue += " \"appId\": \"" + userInfo.appNum + "\", ";
            packageValue += " \"timeStamp\": \"" + timeStamp + "\", ";
            packageValue += " \"nonceStr\": \"" + nonceStr + "\", ";
            packageValue += " \"package\": \"" + string.Format("prepay_id={0}", prepayId) + "\", ";
            packageValue += " \"signType\": \"MD5\", ";
            packageValue += " \"paySign\": \"" + paySign + "\"";
            }
            catch (Exception ex)
            {
                WriteTxt("paypage，异常：" + ex.Message + ",");
            }

        }
        /// <summary>
        /// 微信支付：生成请求数据
        /// </summary>
        /// <param name="ttFee">商品总价格</param>
        /// <param name="busiBody"></param>
        /// <param name="out_trade_no">订单号</param>
        protected void WxPayData(decimal ttFee, string busiBody, string out_trade_no, string code)
        {
            WxPayHelper wxPayHelper = new WxPayHelper();        

            //先设置基本信息
            string partnerId = "1218574001";// "1218574001";//  
            string appId = "wxa9b8e33e48ac5e0f";// "wxa9b8e33e48ac5e0f";// 
            string partnerKey = "huyuxianghuyuxianghuyuxiang12345";// "huyuxianghuyuxianghuyuxiang12345";//  
            //paysignkey(非appkey) 
            string appKey = "nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp"; 
            //"nwRmqgvSG08pe3vU5qzBLb7Bvih0WOABGzUPvqgFqE0iSkJlJ8wh7JlLYy2cXFgFA3v1bM8eTDm1y1UcyeW9IGq2py2qei7J5xDoVR9lfO3cS6fMjFbMQeeqBRit0bKp";// 

            wxPayHelper.SetAppId(appId);
            wxPayHelper.SetAppKey(appKey);
            wxPayHelper.SetPartnerKey(partnerKey);
            wxPayHelper.SetSignType("SHA1");
            //设置请求package信息
            wxPayHelper.SetParameter("bank_type", "WX");
            wxPayHelper.SetParameter("body", busiBody);
            wxPayHelper.SetParameter("attach",busiBody);
            wxPayHelper.SetParameter("partner", partnerId);
            wxPayHelper.SetParameter("out_trade_no", out_trade_no);
            wxPayHelper.SetParameter("total_fee", ((int)(ttFee * 100)).ToString());
            wxPayHelper.SetParameter("fee_type", "1");
           // wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/payment/wxpay/notify_url.aspx?wid="+wid);

            wxPayHelper.SetParameter("notify_url", "http://" + HttpContext.Current.Request.Url.Authority + "/api/wxpay/notify_url.aspx");//不能带参数
            wxPayHelper.SetParameter("spbill_create_ip", "127.0.0.1");
            wxPayHelper.SetParameter("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));

            //---------有效期截至日期------
            wxPayHelper.SetParameter("time_expire", DateTime.Now.AddMinutes(expireMinute).ToString("yyyyMMddHHmmss"));

            wxPayHelper.SetParameter("input_charset", "UTF-8");
            packageValue = wxPayHelper.CreateBizPackage();


        }


        /// <summary>
        /// 记录bug，以便调试
        /// </summary>
        /// 
        /// <returns></returns>
        public bool WriteTxt(string str)
        {
            try
            {
                FileStream fs = new FileStream(Server.MapPath("/shallWeChat/bugLog.txt"), FileMode.Append);
                StreamWriter sw = new StreamWriter(fs);
                //开始写入
                sw.WriteLine(str);
                //清空缓冲区
                sw.Flush();
                //关闭流
                sw.Close();
                fs.Close();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
    }
}